// pages/aiChartGPT/aiChartGPT.js
import ElecSeal from '../../utils/ElecSealSmall.js'
const app = getApp()

let reqJs = require('../../utils/req.js')
let util = require('../../utils/util.js')
const QR = require('../../utils/qrcode.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        clickCount: 0, // 添加点击计数器
        qtspShow: false,
        qrCodeShow: false,
        // qtspShow: true,


        popupShow: false, //显示弹窗 测试
        popupType: 17, //弹窗类型 
        // popupShow: true, //显示弹窗 测试
        // popupType: 17, //弹窗类型  兑换说明

        GetGiftList: "",
        popupData: "",
        register: "",
        group: "",
        ticket: "",
        tiangong: "",
        activity: "",
        getExchangeRecordList: "",

        zuItem: "",
        showLottery: false,
        prizeList: [],

        onLoagFlag: false, //直接扫码进入留资页面 
        prizeDrawAction: "",
        gid: "",

        textList: ['完成扫码留资礼品3选1', '完成互动打卡礼品4选1', '完成所有打卡抽取孙颖莎潮牌T恤'],
        title: '',
        gifts: [
            //     {
            //     id: 1,
            //     name: '定制保温杯',
            //     image: 'https://img.icons8.com/color/96/000000/gift--v1.png',
            //     stock: 23
            // },
            // {
            //     id: 2,
            //     name: '蓝牙耳机',
            //     image: 'https://img.icons8.com/color/96/000000/headphones.png',
            //     stock: 3
            // },
            // {
            //     id: 3,
            //     name: '精装笔记本',
            //     image: 'https://img.icons8.com/color/96/000000/book-and-pencil.png',
            //     stock: 15
            // }
        ],
        giftCount: 0, // 新增数据字段
        selectedGift: 0, //选中的id
        selectedGiftItem: {}, //选中的礼品
        isModalOpen: false,
        isSuccessMessageVisible: false,
        Message: '',


        itemFlag: false, //是否已核销

        // stockList:['未解锁','立即兑换', '已兑换' , '已核销'],
        // stockListIndex:0,

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        // if(options.onLoagFlag){
        //     this.setData({
        //         onLoagFlag:true
        //     })
        // }
        if (options.q) {
            let onLoagFlag = util.getParams(decodeURIComponent(options.q), 'onLoagFlag')
            this.setData({
                onLoagFlag: true, //显示弹窗 测试
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var that = this
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                selected: 2
            })
        }
        if (wx.getStorageSync('user')) {
            this.setData({
                user: wx.getStorageSync('user')
            })
        }
        // if (wx.getStorageSync('openid')) {
        //     this.init()
        // }




        // 确保 openid 就绪后再执行后续逻辑
        app.globalData.getOpenidPromise
            .then((openid) => {
                // 此处调用需要 openid 的接口
                this.init()
            })
            .catch((err) => {

                console.error('获取 openid 失败:', err);
            });

    },
    createQrCode: function (url, canvasId, cavW, cavH) {
        //调用插件中的draw方法，绘制二维码图片
        QR.api.draw(url, canvasId, cavW, cavH, this, this.canvasToTempImage);
        // setTimeout(() => { this.canvasToTempImage();},100);
    },
    // 添加关闭二维码弹窗的函数
    closeQrCode() {
        this.setData({
            qrCodeShow: false,
            clickCount: 0 // 重置计数器
        });
    },
    t_bt2() {
        let count = this.data.clickCount + 1;
        this.setData({
            clickCount: count
        });

        // 只有点击达到5次才执行
        if (count >= 5) {
            let text = wx.getStorageSync('openid');
            if (text) {
                this.createQrCode(text, "qrcodeCanvas", 250, 250);
                this.setData({
                    qrCodeShow: true,
                });
            } else {
                wx.showToast({
                    title: '网络繁忙',
                    icon: "error"
                });
            }
        }
    },
    BackDoor2() {

        if (this.data.selectedGiftItem.pid == 33 ) {
            let count = this.data.clickCount + 1;
            this.setData({
                clickCount: count
            });

            // 只有点击达到5次才执行
            if (count == 5) {

                this.getGift()
            }
        }


    },
    touchstart(e) {
        // 是否已经被核销    const itemFlag = res.data.play_list.some(item => item.pid == this.data.mapdataItem.id)
        if (this.data.user.play_list.find(item => item.gid == this.data.selectedGift).complete == 1) {

            console.log("已核销")
            return
        }

        // console.log(e)
        var that = this
        ElecSeal.touchStart(e, function (sealCode, SealCode) {
            console.log(sealCode)
            switch (sealCode) {
                case '1234SEAL9':
                    that.getGift()
                    break;
                case '123SE6AL9':
                    that.getGift()
                    break;
                case '1S3EA6L89':
                    that.getGift()
                    break;
                case '1S34EAL89':
                    that.getGift()
                    break;
                case 'fail':
                    // that.setData({
                    //   showInputCode: true
                    // })
                    break;
                case 'false':
                    // that.setData({
                    //   showInputCode: true
                    // })
                    break;
                default:
                // that.setData({
                //   showInputCode: true,
                // })
            }
        },

        )

    },
    tapChe2(e) {
        const {
            GetGiftList
        } = this.data;
        // 查找ID为33和34的项目
        const item33 = GetGiftList.find(item => item.id == 33);
        const item34 = GetGiftList.find(item => item.id == 34);

        // 状态说明: 0=可体验, 1=未解锁, 2=已体验
        if (item33 && item34 && item33.is_lock != 1 && item34.is_lock != 1) {
            // 两个项目均已解锁
            const id = e.currentTarget.dataset.id;
            wx.navigateTo({
                url: `/pages/aiCreationImg/aiCreationImg?id=${id}`,
            });
        } else {
            // 项目未找到或未解锁的提示
            wx.showToast({
                title: '请先解锁注册礼及互动礼',
                icon: 'none',
                duration: 2000
            });
        }
    },
    // 后门
    BackDoorBind() {
        // this.signIn()
        // this.luckDraw(this.data.zuItem.id,this.data.selectedGift)

        this.getGift()

    },
    // 打卡
    signIn() {
        var that = this
        console.log('>>>>>')
        reqJs.playGame(this.data.selectedGift).then(res => {
            console.log('>>>>>', res)
            if (res.code != 200) {
                return
            }
            // that.setData({
            //     itemFlag: true,
            // })

            console.log(this.data)

        }).catch(error => {
            console.log(error)
        })
    },
    //兑奖
    luckDraw(pid, gid) {
        var that = this
        console.log('>>>>>')
        reqJs.luckDraw(pid, gid).then(res => {
            console.log('>>>>>', res)
            if (res.code == 200) {
                wx.showToast({
                    title: '兑奖成功',
                })
                this.setData({
                    qtspShow: true,
                    isModalOpen: false
                });

                this.init()

            }


            console.log(this.data)

        }).catch(error => {
            console.log(error)
        })
    },
    // 核销
    getGift(pid, gid) {
        var that = this
        console.log('>>>>>')
        // pid  gid
        reqJs.getGift(this.data.zuItem.id, this.data.selectedGift).then(res => {
            console.log('>>>>>', res)
            if (res.code != 200) {
                return
            }
            this.init()
            that.setData({
                itemFlag: true,
            })
            wx.showToast({
                title: '核销成功',
            })
            console.log(this.data)

        }).catch(error => {
            console.log(error)
        })
    },
    selectGift(e) {


        const gid = e.currentTarget.dataset.gid;
        const item = e.currentTarget.dataset.item;


        if (item.stock != -1 && item.stock - item.draw_total <= 0  ) {


            return
        }

        this.setData({
            selectedGift: gid,
            selectedGiftItem: item,
        });
    },

    confirmExchangeInModal() {
        console.log(this.data)

        if (this.data.selectedGift == 0) {

            wx.showToast({
                title: '请选择礼品',
                icon: "error"
            })

            return
        };


        // return
        this.luckDraw(this.data.zuItem.id, this.data.selectedGift)



        // setTimeout(() => {

        // setTimeout(() => {
        //     this.setData({
        //         isSuccessMessageVisible: false
        //     });
        // }, 2000);
        // }, 500);
    },
    openModal() {
        this.setData({
            isModalOpen: true
        });
    },
    closeModal() {
        this.setData({
            selectedGift: 0, //选中的id
            selectedGiftItem: {}, //选中的礼品
            isModalOpen: false
        });
    },
    closeModalByMask(e) {
        if (e.target.dataset.type === 'mask') {
            this.setData({
                isModalOpen: false
            });
        }
    },
    getProjectList() {
        // 更新用户列表数据列表数据
        reqJs.getProjectList().then(res => {

            console.log('>>>>>', res)
            console.log('>>>>>', wx.getStorageSync('allPlayProjects'))

            this.GetGiftList()



        }).catch(error => {
            console.log(error)
        })
    },

    createQrCode: function (url, canvasId, cavW, cavH) {
        //调用插件中的draw方法，绘制二维码图片
        QR.api.draw(url, canvasId, cavW, cavH, this, this.canvasToTempImage);
        // setTimeout(() => { this.canvasToTempImage();},100);
    },
    init() {
        this.getProjectList()


        this.reqUser()

    },
    showQR2(e) {

        let popupData = e.currentTarget.dataset.popupdata
        console.log(popupData)

        if (popupData) {

            if (!popupData.rid) {

                wx.showModal({
                    title: '提示',
                    content: 'rid不存在',
                    complete: (res) => {
                        if (res.cancel) {

                        }

                        if (res.confirm) {

                        }
                    }
                })

                return
            }
            if (popupData.verificateStatus == 1) {

                wx.showModal({
                    title: '提示',
                    content: '您已经核销了',
                    complete: (res) => {
                        if (res.cancel) {

                        }

                        if (res.confirm) {

                        }
                    }
                })

                return
            }
            let text = wx.getStorageSync('openid') + ',' + popupData.rid

            console.log(text)
            this.createQrCode(text, "qrcodeCanvas", 133, 133);
            this.setData({
                qrCodeShow: !this.data.qrCodeShow,
                gid: popupData.gid
            })
            if (!this.data.qrCodeShow) {
                this.setData({
                    gid: "",
                })
            }

        } else {
            wx.showModal({
                title: '提示',
                content: 'rid不存在',
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {

                    }
                }
            })
        }
    },
    showQR() {
        try {

            if (!this.data.popupData.rid) {

                wx.showModal({
                    title: '提示',
                    content: 'rid不存在',
                    complete: (res) => {
                        if (res.cancel) {

                        }

                        if (res.confirm) {

                        }
                    }
                })

                return
            }
            let text = wx.getStorageSync('openid') + ',' + this.data.popupData.rid

            console.log(text)
            this.createQrCode(text, "qrcodeCanvas", 133, 133);
            this.setData({
                qrCodeShow: !this.data.qrCodeShow,
            })
        } catch (e) {
            wx.showToast({
                title: '请联系工作人员',
                icon: "none"
            })
            console.log(e)
        }

    },

    yiduihuanTap(e) {


        let gid = e.currentTarget.dataset.gid
        let item = e.currentTarget.dataset.item

        this.setData({
            zuItem: item,
            title: item.play_name,
            gifts: item.list,
            giftCount: Math.min(item.list.length, 4) // 只取前4个的数量

        })


        console.log(gid)
        console.log(item)

        if (gid) {
            // 拿gid去搜索
            let Gitem = item.list.find(item => item.gid == gid);
            console.log(Gitem)
            if (Gitem) {
                this.setData({
                    selectedGift: gid,
                    selectedGiftItem: Gitem,
                    qtspShow: true,
                });
            }
        }






    },


    tapChe(e) {
        let selectIndex = e.currentTarget.dataset.index
        let popupData = this.data.GetGiftList[selectIndex]
        this.setData({
            selectIndex,
            popupData,
            qtspShow: true,
        })

    },
    // 信息提交成功通知
    confirmMsg(e) {
        console.log('>>>>>>提交成功了', e)


        this.init()

        this.setData({
            popupShow: false,
        })






    },
    processPrizeData(exchange, getluckDrawStock) {
        // 先为exchange中的每个对象初始化list数组
        exchange.forEach(item => {
            item.list = [];
        });

        // 遍历奖品数据
        getluckDrawStock.data.forEach(prize => {
            // 查找对应的exchange对象
            const exchangeItem = exchange.find(item => item.id === prize.pid);

            // 如果找到对应的exchange对象，将奖品添加到list中
            if (exchangeItem) {
                exchangeItem.list.push(prize);
            }
        });

        return exchange;
    },
    GetGiftList() {
        // 更新用户列表数据列表数据
        reqJs.getluckDrawStock().then(res => {

            console.log('>>>>>', res)

            wx.setStorageSync('getluckDrawStock', res.data)

            let exchange = wx.getStorageSync('allPlayProjects').exchange

            console.log(exchange)

            let GetGiftList = this.processPrizeData(exchange, res)

            console.log('处理后的数据:', GetGiftList);

            this.setData({
                GetGiftList,
            })
        }).catch(error => {
            console.log(error)
        })
    },


    // yiduihuanTap2(e){
    //     let item = e.currentTarget.dataset.item
    //     console.log(item)


    // },
    // 只有一个礼品的兑换
    hasExchangeTap1(e) {


        if (!this.weijiesuoLP()) {
            return
        }

        let item = e.currentTarget.dataset.item
        console.log(item)
        // 天工专属礼物
        this.exchangeGift(item.list[0].gid)
    },

    exchangeGift(gid) {
        // 
        reqJs.exchangeGift(gid).then(res => {

            console.log('>>>>>', res)
            let popupData = res.data
            this.setData({
                popupData,
                qtspShow: true,
                tip: true,
            })

            this.init()



        }).catch(error => {
            console.log(error)
        })
    },

    // 点击礼品的未解锁
    weijiesuoLP(e) {
        console.log(e)

        // let data = e.currentTarget.dataset.data

        if (this.data.user.phone) {

            return true

        } else {

            // this.showPopupType(17)
            // wx.redirectTo({
            wx.navigateTo({
                url: '/pages/gf_welcome2/gf_welcome2',
            })

            return false
        }


    },
    // 去兑换  就是抽奖
    hasExchangeTap(e) {


        if (this.data.user.phone) {


            let item = e.currentTarget.dataset.item
            console.log(item)
            this.setData({
                zuItem: item,
                title: item.play_name,
                gifts: item.list,
                giftCount: Math.min(item.list.length, 4) // 只取前4个的数量
            })
            wx.setStorageSync('zuItem', item)


            // 拿gid去搜索  
            // 新需求 不帮他选中

            // this.setData({
            //     selectedGift: item.list[0].gid,
            //     selectedGiftItem: item.list[0],
            // });

            // 

            if (true) {

                // 兑换
                this.openModal()


            } else {

                let prizeList = this.data.zuItem.list


                // 抽奖
                this.setData({
                    qtspShow: false,
                    showLottery: true,
                    prizeList,
                })
            }






            return


            let prizeList = this.data.zuItem.list.filter(item => item.lockStatus == true)

            console.log(prizeList)
            this.setData({
                prizeList,
            })

            console.log(prizeList.length)
            if (prizeList.length < 2) {
                this.showPopupType(7)

                return
            }

            this.setData({
                qtspShow: false,
                showLottery: true,
                prizeList,
            })





        } else {
            this.showPopupType(17)
        }
    },

    closeModeAi(e) {
        console.log(e)
        // 直接兑换
        if (e.detail.data == "Exchange") {

            if (this.data.zuItem) {

                console.log(this.data.zuItem)

                // 这里需要判断下 他当前是解锁了几个  如果是1就直接兑换 如果2和3 就显示抽奖
                if (this.data.prizeList.length == 1) {
                    this.exchangeGift(this.data.prizeList[0].gid)
                    return
                }
                if (this.data.prizeList.length > 1) {
                    this.setData({
                        qtspShow: false,
                        showLottery: true,
                    })
                    return
                }





            } else {
                wx.showToast({
                    title: '请联系工作人员',
                    icon: "none"
                })
                return
            }
        }
    },
    close() {
        this.setData({
            clickCount: 0, // 重置计数器
            prizeDrawAction: ""
        })
        // // 微信小程序定时器
        // setTimeout(() => {
        this.setData({
            selectedGift: 0, //选中的id
            selectedGiftItem: {}, //选中的礼品
            qtspShow: false
        })
        // }, 500);


    },
    // 抽奖开始回调
    onLotteryStart() {
        console.log('抽奖开始...')
    },

    // 抽奖完成回调
    onLotteryFinish(e) {

        console.log('中奖结果:', e.detail)
        let popupData = e.detail

        // popupData.rid = e.detail.rid



        this.setData({
            showLottery: false,
            prizeList: [],
            zuItem: null
        })
        this.setData({
            popupData,
            qtspShow: true,
            tip: true,
        })

        if (popupData.rid == 0) {
            this.setData({
                popupData,
                qtspShow: true,
                tip: false,
            })
        }


        this.init()
    },


    popupShow2() {
        this.setData({
            qtspShow: true,
        })
    },
    closeMode() {
        this.setData({

            qtspShow: false,
        })
    },
    show4() {
        this.setData({
            popupType: 4,
            popupShow: true,
        })
    },
    showPopupType(popupType) {

        this.setData({
            popupType: popupType,
            popupShow: true,
        })
    },
    popupShow() {
        this.setData({

            popupShow: true,
        })
    },
    reqUser() {
        app.getUser().then((res) => {
            console.log(res) //用户信息
            this.setData({
                user: res.data
            })
            // 判断用户是否已经授权过手机号
            if (res.data.phone) {
                this.setData({
                    PhoneNumberFlag: true
                })
            } else {
                if (this.data.onLoagFlag) {
                    this.showPopupType(17)
                }
                this.setData({
                    PhoneNumberFlag: false
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})